package com.code2roc.jarmanage.servlet.redis;

import com.code2roc.jarmanage.model.Result;
import com.code2roc.jarmanage.util.CommonUtil;
import com.code2roc.jarmanage.util.ConvertUtil;
import com.code2roc.jarmanage.util.JedisUtil;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

public class UpdateRowServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = Result.okResult();
        HashMap params = CommonUtil.getParamMap(req);
        int dbIndex = ConvertUtil.convert2Int(params.get("dbIndex"));
        String key = ConvertUtil.convert2String(params.get("key"));
        Jedis client = JedisUtil.getClient();
        String keyType = JedisUtil.getKeyType(client, dbIndex, key, true);
        if (keyType.equals("list")) {
            int index = ConvertUtil.convert2Int(params.get("index"));
            String value = ConvertUtil.convert2String(params.get("value"));
            JedisUtil.setList(key, index, value, client, dbIndex);
        } else if (keyType.equals("set")) {
            String value = ConvertUtil.convert2String(params.get("value"));
            String newValue = ConvertUtil.convert2String(params.get("newValue"));
            JedisUtil.delSet(key, value, client, dbIndex);
            JedisUtil.setSet(key, newValue, client, dbIndex);
        } else if (keyType.equals("zset")) {
            String value = ConvertUtil.convert2String(params.get("value"));
            String newValue = ConvertUtil.convert2String(params.get("newValue"));
            double newScore = ConvertUtil.convert2Double(params.get("newScore"));
            JedisUtil.delScoreSet(key, value, client, dbIndex);
            JedisUtil.addScoreSet(key, newValue, newScore, client, dbIndex);
        } else if (keyType.equals("hash")) {
            String hashKey = ConvertUtil.convert2String(params.get("hashKey"));
            String newHashKey = ConvertUtil.convert2String(params.get("newHashKey"));
            String newValue = ConvertUtil.convert2String(params.get("newValue"));
            JedisUtil.delHash(key, hashKey, client, dbIndex);
            JedisUtil.setHash(key, newHashKey, newValue, client, dbIndex);
        }
        resp.getWriter().println(result.toString());
    }
}
